package com.cat.binaryAnswer;
/**
 * @author 曲大人的喵
 * @description https://leetcode.cn/problems/find-longest-special-substring-that-occurs-thrice-ii/
 * @create 2025/8/12 14:42
 * @since JDK17
 */

public class Solution11 {
    boolean check(char[] s, char x, int target) {
        int cnt = 0, n = s.length, sum = 0;
        for (int l = 0, r = 0; r < n; l = ++r) {
            if (x != s[r]) {
                continue;
            }
            while (r < n && x == s[r]) {
                r++;
            }
            if (r - l >= target) {
                sum += r - l - target + 1;
            }

            if (sum >= 3) {
                return true;
            }
        }
        return false;
    }

    int find(char[] s, char x, int last) {
        if (!check(s, x, last)) {
            return 0;
        }
        int l = last, r = s.length, mid;
        while (l + 1 < r) {
            mid = l + (r - l) / 2;
            if (check(s, x, mid)) {
                l = mid;
            } else {
                r = mid;
            }
        }
        return l == 0 ? -1 : l;
    }
    public int maximumLength(String str) {
        char[] s = str.toCharArray();
        int ans = 0;
        for (int i = 0; i < 26; i++) {
            ans = Math.max(ans, find(s, ((char) (i + 'a')), ans));
        }
        return ans == 0 ? -1 : ans;
    }
}
